package com.example.apple.paopo.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;

import com.baoyz.actionsheet.ActionSheet;
import com.example.apple.paopo.R;
import com.example.apple.paopo.base.BaseActivity;
import com.example.apple.paopo.dialog.PaoPoDialog;
import com.orhanobut.logger.Logger;
import com.vondear.rxtools.RxNetTool;
import com.vondear.rxtools.view.RxToast;
import com.zyao89.view.zloading.ZLoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * Created by apple on 17/11/30.
 */
@ContentView(R.layout.activity_login)
public  class LoginActivity extends BaseActivity {
    @ViewInject(R.id.login_et_username)
    EditText et_username;
    @ViewInject(R.id.login_et_password)
    EditText et_password;
    SharedPreferences sharedPreferences;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        sharedPreferences =getSharedPreferences("PAOPO",MODE_APPEND);
    }
    //登录
    @Event(R.id.login_btn_login)
    private void loginAction(View v){
        if(!RxNetTool.isNetworkAvailable(this)){
            RxToast.error(this,"登录失败，请检查网络是否可用").show();
        }else {
            //http://cloud.bmob.cn/91c9d2dffacfcd37/userLoginAction
            final ZLoadingDialog dialog = PaoPoDialog.getPaoPoDialog(LoginActivity.this,"正在登录PAOPO,请稍后...");
            RequestParams params = new RequestParams("http://cloud.bmob.cn/91c9d2dffacfcd37/userLoginAction");
            params.addQueryStringParameter("user",et_username.getText().toString());
            params.addQueryStringParameter("pwd",et_password.getText().toString());
            x.http().get(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    //解析result
                    try {
                        JSONObject jsonObject =new JSONObject(result);
                        if (jsonObject.getString("state").equals("YES")){
                            SharedPreferences.Editor editor =sharedPreferences.edit();
                            editor.putString("username",jsonObject.getString("username"));
                            editor.putString("nick",jsonObject.getString("nick"));
                            editor.putString("avatar",jsonObject.getString("avatar"));
                            editor.putString("token",jsonObject.getString("token"));
                            editor.commit();
                            Logger.d(jsonObject.toString());
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));

                          //  EventBus.getDefault().postSticky("sdasf");
                            RxToast.success("登录成功");
                            dialog.cancel();
                            dialog.dismiss();
                            finish();
                        }else {
                            RxToast.error("账号密码错误，请重新输入");
                            dialog.cancel();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        dialog.cancel();
                    }
                }
                //请求异常后的回调方法
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    RxToast.error("登录失败，请检查网络");
                    dialog.dismiss();
                }
                //主动调用取消请求的回调方法
                @Override
                public void onCancelled(CancelledException cex) {
                    dialog.dismiss();
                }
                @Override
                public void onFinished() {
                    dialog.dismiss();
                }
            });

//            AsyncCustomEndpoints ace = new AsyncCustomEndpoints();
//            //第一个参数是云函数的方法名称，
//            // 第二个参数是上传到云函数的参数列表（JSONObject cloudCodeParams），
//            // 第三个参数是回调类
//            JSONObject params = new JSONObject();
//            try {
//                params.put("user", et_username.getText().toString());
//                params.put("pwd", et_password.getText().toString());
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//            ace.callEndpoint("userLoginAction", params, new CloudCodeListener() {
//                @Override
//                public void done(Object object, BmobException e) {
//                    if (e == null) {
//                        try {
//                            JSONObject jsonObject =new JSONObject(object.toString());
//
//                        } catch (JSONException e1) {
//                            e1.printStackTrace();
//                        }
//                        Logger.d(object.toString());
//                    } else {
////                    Log.e(TAG, " " + e.getMessage());
//                        Logger.d(e.getMessage());
//
//                    }
//                }
//            });
        }
    }

    //注册
    @Event(R.id.login_tv_register)
    private void registerAction(View v){
        Intent intent  = new Intent(this,RegisteredActivity.class);
        startActivity(intent);
    }

    //密码找回
    @Event(R.id.login_tv_forgetPassword)
    private void forgetPasswordAction(View v){
        ActionSheet.createBuilder(this,getSupportFragmentManager())
                .setCancelButtonTitle("取消")
                .setOtherButtonTitles("短信找回","邮箱找回")
                .setCancelableOnTouchOutside(true)
                .setListener(new ActionSheet.ActionSheetListener() {
                    @Override
                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                    }

                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                        switch (index){
                            case 0:
                                Intent intentphone  = new Intent(LoginActivity.this,ForgetPasswordPhoneActivity.class);
                                startActivity(intentphone);
                                actionSheet.dismiss();
                                break;
                            case 1:
                                Intent intentemail  = new Intent(LoginActivity.this,ForgetPasswordEmailActivity.class);
                                startActivity(intentemail);
                                actionSheet.dismiss();
                                break;
                        }
                    }
                }).show();

    }

    @Event(R.id.login_tv_serviceTerms)
    private void serviceTermsAction(View v ){
        RxToast.success("sdasf");
//        ZLoadingDialog dialog = new ZLoadingDialog(LoginActivity.this);
//        dialog.setLoadingBuilder(Z_TYPE.LEAF_ROTATE)//设置类型
//                .setLoadingColor(Color.BLACK)//颜色
//                .setHintText("Loading...")
//                .setHintTextSize(16) // 设置字体大小 dp
//                .setHintTextColor(Color.GRAY)  // 设置字体颜色
//                .show();

    }

}
